package com.vehicle.service.Impl;

import com.vehicle.domains.bo.QuerySnapshotBo;
import com.vehicle.domains.entity.CameraSnapshotEntity;
import com.vehicle.mapper.CameraSnapshotMapper;
import com.vehicle.service.CameraSnapshotService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class CameraSnapshotServiceImpl implements CameraSnapshotService {
    @Resource
    private CameraSnapshotMapper cameraSnapshotMapper;
    @Override
    public void storeSnapshotImage(String url, String ip) {
        CameraSnapshotEntity cameraSnapshotEntity = new CameraSnapshotEntity();
        cameraSnapshotEntity.setCameraIp(ip);
        cameraSnapshotEntity.setSnapshotUrl(url);
        cameraSnapshotEntity.setSnapshotTime(new Date());
        cameraSnapshotMapper.insertCameraSnapshot(cameraSnapshotEntity);
    }

    @Override
    public String getLastSnapshot(String cameraIp, Date date) {
        CameraSnapshotEntity cameraSnapshotEntity = cameraSnapshotMapper.selectLatestSnapshotByCameraIp(cameraIp, date);
        if (cameraSnapshotEntity == null) {
            return null;
        }
        return cameraSnapshotEntity.getSnapshotUrl();
    }

    @Override
    public List<CameraSnapshotEntity> queryBySnapshotBo(QuerySnapshotBo querySnapshotBo) {
        return cameraSnapshotMapper.queryBySnapshotBo(querySnapshotBo);
    }

    @Override
    public void deleteSnapshot(CameraSnapshotEntity entity) {
        File file = new File(entity.getSnapshotUrl());
        if (file.exists()) {
            boolean delete = file.delete();
            if (!delete) {
                log.info("删除文件失败");
            }
        }else {
            log.info("文件不存在");
        }
        cameraSnapshotMapper.deleteById(entity.getId());
    }
}
